﻿@{
    ViewBag.Title = "Form";
    Layout = "~/Views/Shared/_Form.cshtml";
}
@using LeSoft.Application.Code;

<link href="~/Content/scripts/plugins/jqgrid/jqgrid.css" rel="stylesheet" />
<script src="~/Content/scripts/plugins/jqgrid/jqgrid.js"></script>
<script>
    var keyValue = request('keyValue');
    var _SPIId = request('SPIId');
    var _PStructId = "";
    var _rowid = 1;
    var _organizeId = "@OperatorProvider.Provider.Current().CompanyId";
    $(function () {
        GetGrid();
        GetGrid1();
        initControl();
    })
    //初始化控件
    function initControl() {
        //组织机构
        $("#Organize").ComboBoxTree({
            url: "../../BaseManage/Organize/GetTreeJsonById",
            description: "==请选择==",
            height: "200px",
            click: function (item) {
                if (item.id != _organizeId) {
                    _organizeId = item.id;
                    GetTree();
                }
            }
        });
        if (_organizeId != "") $("#Organize").ComboBoxSetValue(_organizeId);
        //项目
        $("#SPIId").ComboBoxTree({
            url: "../../PropertyManage/SecurityPatrol/GetTreeListItem",
            description: "==请选择==",
            height: "230px",
            click: function (item) {
                if (_SPIId != item.id)
                    _SPIId = item.id;
            }
        });
        $("#SPIId").ComboBoxTreeSetValue(_SPIId);
        GetTree();
        //获取表单
        if (!!keyValue) {
            $.SetForm({
                url: "../../PropertyManage/SecurityPatrol/GetLineEntity",
                param: { keyValue: keyValue },
                success: function (data) {
                    $("#form1").SetWebControls(data);
                    _organizeId = data.CompanyId;
                    $("#Organize").ComboBoxTreeSetValue(data.CompanyId);

                    _SPIId = data.SPIId;
                    $("#SPIId").ComboBoxTreeSetValue(data.SPIId);
                    _PStructId = data.PStructId;
                    $("#PStructId").ComboBoxTreeSetValue(data.PStructId);
                    GetAreaGrid();
                    GetLineDetail();
                }
            });
        }
    }

    function GetTree() {
        //楼盘信息
        $("#PStructId").ComboBoxTree({
            url: "../../ResourceManage/RS_PStructs/GetTypeTreeJson?type=1&OrganizeId=" + _organizeId,
            description: "==请选择==",
            height: "230px",
            click: function (item) {
                if (_PStructId != item.id) {
                    _PStructId = item.id;
                    GetReloadGrid();
                }
            }
        });
    }

    //加载表格
    function GetGrid() {
        var selectedRowIndex = 0;
        var $gridTable = $('#gridTable');
        $gridTable.jqGrid({
            datatype: "json",
            height: 430,
            autowidth: true,
            colModel: [
                { label: "主键", name: "PCode", index: "PCode", hidden: true },
                { label: "编号", name: "EnCode", index: "EnCode", width: 50, align: "center" },
                { label: "名称", name: "Name", index: "Name", width: 100, align: "center" },
                { label: "位置描述", name: "OtherCode", index: "OtherCode", width: 150, align: "center" }
            ],
            viewrecords: true,
            rownumbers: true,
            rowNum: 1000,
            shrinkToFit: false,
            gridview: true,
            onSelectRow: function (status) {
                selectedRowIndex = $("#" + this.id).getGridParam('selrow');
            },
            gridComplete: function () {
                $("#" + this.id).setSelection(selectedRowIndex, false);
            },
            ondblClickRow: function (rowid, iRow, iCol, e) {
                var obj = $("#" + this.id).getRowData(rowid);
                obj["PuctureFlag"] = 1;
                $('#gridTable1').addRowData(_rowid, obj);
                _rowid++;
            }
        });
    }

    //加载表格
    function GetGrid1() {
        var selectedRowIndex = 0;
        var $gridTable = $('#gridTable1');
        $gridTable.jqGrid({
            datatype: "json",
            height: 430,
            autowidth: true,
            colModel: [
                { label: "主键", name: "PCode", index: "PCode", hidden: true },
                { label: "内容主键", name: "SPContentId", index: "SPContentId", hidden: true },
                {
                    label: " ", name: "delete", index: "delete", width: 30, align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return "<a onclick=\"RemoveGrid(" + options.rowId + ");\"><i class=\"fa fa-trash\"></i>&nbsp;</a>"
                    }
                },
                { label: "编号", name: "EnCode", index: "EnCode", width: 50, align: "center" },
                { label: "名称", name: "Name", index: "Name", width: 100, align: "center" },
                { label: "位置描述", name: "OtherCode", index: "OtherCode", width: 150, align: "center" },
                {
                    label: "是否拍照", name: "PuctureFlag", index: "PuctureFlag", width: 50, align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return cellvalue == 1 ? "<i class=\"fa fa-toggle-on\"></i>" : "<i class=\"fa fa-toggle-off\"></i>";
                    },
                },
                { label: "明细主键", name: "SPLDId", index: "SPLDId", hidden: true }
            ],
            viewrecords: true,
            rownumbers: true,
            shrinkToFit: false,
            hidegrid: false,
            rowNum: 1000,
            unwritten: false,
            onSelectRow: function (status) {
                selectedRowIndex = $("#" + this.id).getGridParam('selrow');
            },
            onCellSelect: function (rowid, iCol, cellcontent, e) {
                if (iCol == 8) {
                    if (cellcontent == "<i class=\"fa fa-toggle-on\"></i>") $gridTable.setCell(rowid, iCol, "0");
                    else $gridTable.setCell(rowid, iCol, "1");
                }
            },
            gridComplete: function () {
                $("#" + this.id).setSelection(selectedRowIndex, false);
            },
            //ondblClickRow: function (rowid, iRow, iCol, e) {
            //    //if (!_SPIId) {
            //    //    dialogMsg("请选择巡更项目。", 0);
            //    //}
            //    //else {
            //    dialogOpen({
            //        id: "ContentForm",
            //        title: '关联巡检内容',
            //        url: '/PropertyManage/SecurityPatrol/ContentSelectContent?SPIId=' + _SPIId + "&rowid=" + rowid + "&SPContentId=" + $("#gridTable1").jqGrid('getRowData', rowid)['SPContentId'],
            //        width: "1100px",
            //        height: "550px",
            //        callBack: function (iframeId) {
            //            top.frames[iframeId].AcceptClick();
            //        }
            //    });
            //    //}
            //},
            subGrid: true,
            subGridRowExpanded: function (subgrid_id, row_id) {
                var SPContentIds = $("#gridTable1").jqGrid('getRowData', row_id)['SPContentId'];
                var subgrid_table_id = subgrid_id + "_t";
                var subhtml = "";
                subhtml += '<div><table id="' + subgrid_table_id + '"></table></table></div>';
                $("#" + subgrid_id).html(subhtml);
                $("#" + subgrid_table_id).jqGrid({
                    caption: "巡更内容",
                    datatype: "json",
                    height: 100,
                    colModel: [
                        { label: "主键", name: "Id", index: "Id", hidden: true },
                        {
                            label: " ", name: "delete", index: "delete", width: 30, align: "center",
                            formatter: function (cellvalue, options, rowObject) {
                                return "<a onclick=\"RemoveGrid1(" + options.rowId + ",'" + subgrid_table_id + "'," + row_id + ");\"><i class=\"fa fa-trash\"></i>&nbsp;</a>"
                            }
                        },
                        { label: "编号", name: "Code", index: "Code", width: 60, align: "center" },
                        { label: "名称", name: "Name", index: "Name", width: 70, align: "center" },
                        {
                            label: "类型", name: "Type", index: "Type", width: 70, align: "center",
                            formatter: function (cellvalue, options, rowObject) {
                                return cellvalue == 0 ? "录入型" : "选择型";
                            }
                        },
                        {
                            label: "内容明细", name: "TypeDescription", index: "TypeDescription", width: 200, align: "left",
                            formatter: function (cellvalue, options, rowObject) {
                                var _Html = "";
                                _Html += "<p style=\"padding-left:15px;\">检查方法：" + rowObject.CheckWay + "&nbsp;&nbsp;&nbsp;标准要求：" + rowObject.Criterion + "</p>";
                                var list = eval('(' + cellvalue + ')');
                                if (rowObject.Type == 1) {
                                    $.each(list, function (index, item) {
                                        _Html += "<div style=\"float: left; margin-left: 20px;\">" + item.Text + "</div>";
                                    });
                                }
                                return _Html;
                            }
                        },
                    ],
                    pager: false,
                    rowNum: "1000",
                    rownumbers: true,
                    hidegrid: false,
                    shrinkToFit: false,
                    gridview: true
                });
                //获取表单
                if (!!SPContentIds) {
                    $.SetForm({
                        url: "/PropertyManage/SecurityPatrol/GetContentList",
                        param: { ids: SPContentIds },
                        success: function (data) {
                            $("#" + subgrid_table_id)[0].addJSONData(data);
                        }
                    });
                }
            }
        });
    }

    function GetLineDetail() {
        $.SetForm({
            url: "../../PropertyManage/SecurityPatrol/GetAreaBySPLID",
            param: { SPLId: keyValue },
            success: function (data) {
                $("#gridTable1")[0].addJSONData(data);
                _rowid = $("#gridTable").jqGrid("getRowData").length + 1;
            }
        });
    }

    function RemoveGrid(rowid) {
        //var obj = $('#gridTable1').getRowData(rowid);
        //$('#gridTable').addRowData(rowid, obj);
        $('#gridTable1').delRowData(rowid);
    }

    function RemoveGrid1(rowid, tableId, row_id) {
        
        var id = $('#' + tableId).getRowData(rowid).Id;
        var obj = $('#gridTable1').getRowData(row_id);
        var ids = obj.SPContentId.split(',');
        var spldids = obj.SPLDId.split(',');
        if (!!ids && ids != "") {
            $.each(ids, function (index, model) {
                if (model != "" && model == id) {
                    ids.splice(index, 1);
                    return false;
                }
            });
        }
        //var ids = $('#gridTable1').getRowData(row_id).SPContentId.replace(id + ",", "&nbsp;");
        ids = ids.join(',') == "" ? "&nbsp;" : ids.join(',');
        spldids = spldids.join(',') == "" ? "&nbsp;" : spldids.join(',');
        $("#gridTable1").setCell(row_id, 'SPContentId', ids);
        $("#gridTable1").setCell(row_id, 'SPLDId', spldids);
        $('#' + tableId).delRowData(rowid);
    }


    function TopMost() {
        //var $tr = $(obj).parent().parent();
        var id = $('#gridTable1').jqGrid('getGridParam', 'selrow');
        if (checkedRow(id)) {
            $("#gridTable1 tr td.sgexpanded").trigger("click");
            var $tr = $('#gridTable1 tr#' + id);
            if ($tr.index() != 1)
                $tr.prevAll("tr:last").after($tr);
            $tr.getGridParam('selrow');
        }
    }

    function SortUp() {
        //var $tr = $(obj).parent().parent();
        var id = $('#gridTable1').jqGrid('getGridParam', 'selrow');
        if (checkedRow(id)) {
            $("#gridTable1 tr td.sgexpanded").trigger("click");
            var $tr = $('#gridTable1 tr#' + id);
            if ($tr.index() != 1)
                $tr.prev().before($tr);
            $tr.getGridParam('selrow');
        }
    }


    function SortDown() {
        //var $tr = $(obj).parent().parent();
        var id = $('#gridTable1').jqGrid('getGridParam', 'selrow');
        if (checkedRow(id)) {
            $("#gridTable1 tr td.sgexpanded").trigger("click");
            var $tr = $('#gridTable1 tr#' + id);
            $tr.next().after($tr);
            $tr.getGridParam('selrow');
        }
    }

    function DownMost() {
        //var $tr = $(obj).parent().parent();
        var id = $('#gridTable1').jqGrid('getGridParam', 'selrow');
        if (checkedRow(id)) {
            $("#gridTable1 tr td.sgexpanded").trigger("click");
            var $tr = $('#gridTable1 tr#' + id);
            $tr.nextAll("tr:last").after($tr);
            $tr.getGridParam('selrow');
        }
    }

    function GetAreaGrid() {
        $.SetForm({
            url: "/PropertyManage/SecurityPatrol/GetArea?PStructId=" + _PStructId,
            param: { SPLId: keyValue },
            success: function (data) {
                $("#gridTable")[0].addJSONData(data);
            }
        });
    }


    function GetReloadGrid() {
        var $gridTable = $('#gridTable');
        $gridTable.jqGrid('setGridParam', {
            url: "/PropertyManage/SecurityPatrol/GetArea?PStructId=" + _PStructId,
        }).trigger('reloadGrid');

        $('#gridTable1').jqGrid('clearGridData');
    }
    function AddContent() {
        var keyValue = $("#gridTable1").jqGridRowValue("PCode");
        var rowid =$("#gridTable1").jqGrid('getGridParam', 'selrow');
       // var rowData = $("#gridTable1").jqGrid('getRowData', rowid);
        if (checkedRow(keyValue)) {
            dialogOpen({
                id: "ContentForm",
                title: '关联巡检内容',
                url: '/PropertyManage/SecurityPatrol/ContentSelectContent?SPIId=' + _SPIId + "&rowid=" + rowid + "&SPContentId=" + $("#gridTable1").jqGrid('getRowData', rowid)['SPContentId'],
                width: "1100px",
                height: "550px",
                callBack: function (iframeId) {
                    top.frames[iframeId].AcceptClick();
                }
            });
        }
    }
    //保存表单
    function AcceptClick() {
        if (!$('#form1').Validform()) {
            return false;
        }
        var postData = $("#form1").GetWebControls(keyValue);
        postData["SPIId"] = _SPIId;
        postData["PStructId"] = _PStructId;
        postData["CompanyId"] = _organizeId;
        delete postData["undefined"];
        var SecurityPatrolLineDetail = [];
        var obj = $("#gridTable1").jqGrid("getRowData");
        var sort = 1;
        
        if (obj.length > 0) {
            for (var i = 0; i < obj.length; i++) {
                var ids = obj[i].SPContentId.split(',');
                var spldids = obj[i].SPLDId.split(',');
                if (!!ids && ids != "") {
                    $.each(ids, function (index, model) {
                        if (model != "") {
                            var item = {};
                            item["PStructId"] = obj[i].PCode;
                            item["PuctureFlag"] = obj[i].PuctureFlag == "<i class=\"fa fa-toggle-on\"></i>" ? 1 : 0;
                            item["Sort"] = sort;
                            item["SPContentId"] = model;
                            if (spldids != null && spldids != "" && spldids.length > index)
                                item["SPLDId"] = spldids[index];
                            if (!!keyValue)
                                item["SPLId"] = keyValue;
                            SecurityPatrolLineDetail.push(item);
                        }
                    });
                    sort++;
                }
                else {
                    var item = {};
                    item["PStructId"] = obj[i].PCode;
                    item["PuctureFlag"] = obj[i].PuctureFlag == "<i class=\"fa fa-toggle-on\"></i>" ? 1 : 0;
                    item["Sort"] = sort;
                    item["SPLDId"] = spldids[0];
                    if (!!keyValue)
                        item["SPLId"] = keyValue;
                    SecurityPatrolLineDetail.push(item);
                    sort++;
                }
            }
        }
        $.SaveForm({
            url: "../../PropertyManage/SecurityPatrol/SaveForm?keyValue=" + keyValue,
            param: { SecurityPatrolLine: JSON.stringify(postData), SecurityPatrolLineDetail: JSON.stringify(SecurityPatrolLineDetail) },
            loading: "正在保存数据...",
            success: function () {
                $.currentIframe().$("#gridTable").trigger("reloadGrid");
            }
        })
    }
</script>
<div style="margin-top: 20px; margin-right: 30px;">
    <table class="form">
        <tr>
            <th class="formTitle">所属机构<font face="宋体">*</font></th>
            <td class="formValue">
                <div id="Organize" type="select" class="ui-select" isvalid="yes" checkexpession="NotNull"></div>
            </td>
            <th class="formTitle">所属项目<font face="宋体">*</font>：</th>
            <td class="formValue">
                <div id="SPIId" type="selectTree" class="ui-select" isvalid="yes" checkexpession="NotNull"></div>
            </td>
        </tr>
        <tr>
            <th class="formTitle">线路名称<font face="宋体">*</font>：</th>
            <td class="formValue">
                <input id="Name" type="text" onblur="$.ExistField(this.id, '../../PropertyManage/SecurityPatrol/ExistLineName')" class="form-control" placeholder="请输入名称" isvalid="yes" checkexpession="NotNull" />
            </td>
            <th class="formTitle">线路编号<font face="宋体">*</font>：</th>
            <td class="formValue">
                <input id="Code" type="text" onblur="$.ExistField(this.id, '../../PropertyManage/SecurityPatrol/ExistLineCode')" class="form-control" placeholder="请输入编号" isvalid="yes" checkexpession="NotNull" />
            </td>
        </tr>
        <tr>
            <th class="formTitle">所属楼盘<font face="宋体">*</font>：</th>
            <td class="formValue">
                <div id="PStructId" type="selectTree" class="ui-select" isvalid="yes" checkexpession="NotNull"></div>
            </td>
        </tr>
        <tr>
            <th class="formTitle" style="height: 37px;">线路点：</th>
            <td class="formValue" colspan="2"></td>
            <td style="text-align:right;">
            <a id="lr-add" class="btn btn-default"onclick="AddContent()"><i class="fa fa-plus"></i>&nbsp;添加内容</a></td>
        </tr>
        <tr>
            <td class="formValue"></td>
            <td class="formValue">
                <div style="width:80%;float:left;"><table id="gridTable"></table></div>
                <div style="width: 20%; float: right; text-align: center; line-height:475px;height:475px;"><i class="fa fa-exchange"></i></div>
            </td>
            <td class="formValue" colspan="2">
                <div style="width:90%;float:left;">
                    <table id="gridTable1"></table>
                </div>
                <div style="width: 10%; float: right;">
                    <a class="btn btn-default" onclick="TopMost();"><i class="fa fa-arrow-up"></i>最上</a><br />
                    <a class="btn btn-default" onclick="SortUp();"><i class="fa fa-arrow-up"></i>向上</a><br />
                    <a class="btn btn-default" onclick="SortDown();"><i class="fa fa-arrow-down"></i>向下</a><br />
                    <a class="btn btn-default" onclick="DownMost();"><i class="fa fa-arrow-down"></i>最下</a><br />
                </div>
            </td>
        </tr>
    </table>
</div>
<script src="~/Content/scripts/plugins/Sortable-master/Sortable.min.js"></script>
<script src="~/Content/scripts/plugins/Sortable-master/app.js"></script>